package test.jardependecne;

import java.io.*;

/**
 * Created by linshuo on 2017/12/12.
 * 读取PackJar.jar下的/src/files/123.txt
 */
public class JarResourcePath {
    public final static String path1 = "files/123.txt";

    public static void main(String[] args) throws IOException {
        System.out.println(readFileClassLoader());
    }

    /**
     * jar包资源的读取得用classloader, 注意相对路径为"files/123.txt"而不是"src/files/123.txt"
     *
     * @return
     * @throws IOException
     */
    public static String readFileClassLoader() throws IOException {
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path1);
        Reader reader = new BufferedReader(new InputStreamReader(inputStream));
        char[] buffer = new char[1024];
        reader.read(buffer);
        return String.valueOf(buffer);
    }


    /**
     * 直接利用相对路径读取会报错, 即找不到文件
     *
     * @return
     * @throws IOException
     */
    public static String readFileNormal() throws IOException {
        Reader reader = new BufferedReader(new FileReader(path1));
        char[] buffer = new char[1024];
        reader.read(buffer);
        return String.valueOf(buffer);
    }
}
